package com.example.doc.controller;

import com.example.doc.core.utils.FileUtils;
import com.example.doc.model.FileInfo;
import com.example.doc.model.Train;
import com.example.doc.service.TrainService;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.UnsupportedEncodingException;
import java.util.List;

@RestController
@RequestMapping("/train")
public class TrainController {

    @Resource
    TrainService trainService;

    @GetMapping
    public List<Train> getTrainAll(){
        return trainService.getTrainAll();
    }

    @PostMapping("/upload")
    public void uoloadFile(MultipartFile file){
//        String filename = file.getOriginalFilename();
//        String resourcePath = FileUtils.getServerPath();
////        String filePath = "E:/data/";
////        File dest = new File(filePath + filename);
//        String path = "/upload/"+filename;
//        FileUtils.createFolderIfNotExist(resourcePath + path);
//        FileUtils.transferFile(file,resourcePath + path);
//        System.out.println(filename);
        FileInfo fileInfo = FileUtils.uploadFile(file,"train");

        Train train = new Train();
        train.setFilename(fileInfo.getFilename());
        train.setFilepath(fileInfo.getFilepath());
        trainService.addTrain(train);
    }

//    @PostMapping("/download")
//    public void doDownload(HttpServletResponse response,String filepath){
//        filepath = FileUtils.getServerPath() + filepath;
//        FileUtils.downloadFile(response,filepath);
//    }

//    @PostMapping("/download")
//    public void doDownload(HttpServletResponse response,@RequestBody FileInfo fileInfo){
//        String filepath = FileUtils.getServerPath() + fileInfo.getFilepath();
//        FileUtils.downloadFile(response,filepath);
//    }

//    @PostMapping("/download")
//    public void doDownload(HttpServletRequest request,HttpServletResponse response, @RequestBody FileInfo fileInfo){
//        try {
//            String filepath = FileUtils.getServerPath() + fileInfo.getFilepath();
//
//            response.setCharacterEncoding("utf-8");
//            response.setContentType("multipart/form-data");
//            response.setHeader("Content-Disposition","attachment;fileName=" + FileUtils.setFileDownloadHeader(request, fileInfo.getFilename()));
//            FileUtils.writeBytes(filepath,response.getOutputStream());
////            FileUtils.downloadFile(response,filepath);
//        } catch (Exception e) {
//            e.printStackTrace();
//        }
//    }

}
